package com.si.sea_island.utils;


import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

public class SmsUtils {
    private static final String SYMBOLS = "0123456789"; // 数字

    private static final Random RANDOM = new SecureRandom();


    public static String getRandomSMS() {
        // 如果需要4位，那 new char[4] 即可，其他位数同理可得
        char[] nonceChars = new char[6];

        for (int index = 0; index < nonceChars.length; ++index) {
            nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
        }
        return new String(nonceChars);
    }

    public static boolean sendSMS(String phone, String savaCode) throws Exception {


        //创建post参数不包含signature 密码不需要md5
        String password = "8944a9ca";

        Map<String, String> paras = new HashMap<>();
        paras.put("sp_id", "656267");
        paras.put("mobile", phone);
        paras.put("content", "【闪磁兽】您的短信验证码是"+savaCode+",请勿发送给他人");
        paras.put("ext", "434510");
        //根据参数Key排序（顺序）
        java.util.TreeMap<String, String> sortParas = new java.util.TreeMap<>();
        sortParas.putAll(paras);

        String sortedQueryString = specialUrlEncode(http_build_query(sortParas));

        //将上面得到的字符串按照如下顺序拼接成新的字符串
        StringBuilder stringToSign = new StringBuilder();
        stringToSign.append("POST").append("&");
        stringToSign.append(toUtf8("/")).append("&");
        stringToSign.append(sortedQueryString);

        //签名采用HmacSHA1算法 + Base64。参考代码如下：
        String sign = getSignature(stringToSign.toString(), password);

        System.out.println(sign);

        int responseCode = 0;

        try {
            URL url = new URL("http://124.221.199.65:9511/api/send-sms-single");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setDoOutput(true);
//            String jsonInputString = "{\"sp_id\":\"656267\"" +
//                    ",\"mobile\":\"13656518665\"" +
//                    ",\"content\":\"【测试】验证码123\"" +
//                    ",\"password\":" +sign+ " }";
            // 构建表单数据
            Map<String, String> formData = new HashMap<>();
            formData.put("sp_id", "656267");
            formData.put("mobile", phone);
            formData.put("content", "【闪磁兽】您的短信验证码是"+savaCode+",请勿发送给他人");
            formData.put("signature", sign);
            formData.put("ext", "434510");
            // 编码表单数据
            String encodedFormData = formData.entrySet().stream()
                    .map(entry -> {
                        try {
                            return entry.getKey() + "=" + java.net.URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8.toString());
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                        return null;
                    })
                    .collect(Collectors.joining("&"));
            // 发送数据
            try (OutputStream os = connection.getOutputStream()) {
                os.write(encodedFormData.getBytes(StandardCharsets.UTF_8));
            }
            responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);
            // 你可以进一步处理响应，例如读取响应体
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (responseCode==200){
            return true;
        }
        return false;
    }

    public static String toUtf8(String value) throws Exception {
        return java.net.URLEncoder.encode(value, "UTF-8");
    }

    public static String specialUrlEncode(String value) throws Exception {
        return value.replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
    }

    public static String getSignature(String data, String key) throws Exception {
        byte[] keyBytes = key.getBytes();

        SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");

        Mac mac = Mac.getInstance("HmacSHA1");

        mac.init(signingKey);

        byte[] rawHmac = mac.doFinal(data.getBytes());

        String hexBytes = byte2hex(rawHmac);

        return new sun.misc.BASE64Encoder().encode(hexBytes.getBytes());
    }

    private static String byte2hex(final byte[] b) {
        String hs = "";

        String stmp = "";

        for (int n = 0; n < b.length; n++) {

            stmp = (Integer.toHexString(b[n] & 0xFF));

            if (stmp.length() == 1) {
                hs = hs + "0" + stmp;

            } else {
                hs = hs + stmp;

            }

        }

        return hs;

    }

    /**
     * Java实现PHP中的http_build_query()效果
     *
     * @param array key=value形式的二位数组
     * @return
     */
    public static String http_build_query(Map<String, String> array) {
        String reString = null;
        //遍历数组形成akey=avalue&bkey=bvalue&ckey=cvalue形式的的字符串
        Iterator it = array.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> entry = (Map.Entry) it.next();
            String key = entry.getKey();
            String value = entry.getValue();
            reString += key + "=" + value + "&";
        }
        reString = reString.substring(0, reString.length() - 1);
        //将得到的字符串进行处理得到目标格式的字符串
        try {
            reString = java.net.URLEncoder.encode(reString, "utf-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        reString = reString.replace("%3D", "=").replace("%26", "&");

        // 去除第一个多余的null符号
        return reString.substring(4);

    }




}
